package register

import (
	"api/config"
	"api/libs/errs"
	"encoding/json"
	"fmt"
	"gitee.com/dreamwood/ez"
	"io"
	"net/http"
	"net/url"
	"os"
)

type Page struct {
	Name  string  `json:"name" gorm:"size:255;" flag:""`
	Route string  `json:"route" gorm:"size:255;" flag:""`
	Icon  string  `json:"icon" gorm:"size:255;" flag:""`
	Type  string  `json:"type" gorm:"size:255;" flag:""`
	State int     `json:"state" gorm:"" flag:""`
	Sort  int     `json:"sort" gorm:"" flag:""`
	Sons  []*Page `json:"sons"`
}

const confFilePage = "./app_conf_pages.json"
const confFilePageMd5 = "./app_conf_pages.txt"

func NewPage(name string) *Page {
	md := new(Page)
	md.Type = "page"
	md.Name = name
	md.State = 0
	md.Sort = 0
	md.Icon = "extension"
	return md
}
func (p *Page) SetSort(v int) *Page {
	p.Sort = v
	return p
}
func (p *Page) SetIcon(v string) *Page {
	p.Icon = v
	return p
}
func (p *Page) SetName(v string) *Page {
	p.Name = v
	return p
}
func (p *Page) SetRoute(v string) *Page {
	p.Route = v
	return p
}
func (p *Page) IsPage() *Page {
	p.Type = "page"
	return p
}
func (p *Page) IsFunc() *Page {
	p.Type = "func"
	return p
}

func (p *Page) Add(name string) *Page {
	if p.Sons == nil {
		p.Sons = make([]*Page, 0)
	}
	son := NewPage(name)
	p.Sons = append(p.Sons, son)
	return son
}
func (p *Page) AddSon(son *Page) *Page {
	if p.Sons == nil {
		p.Sons = make([]*Page, 0)
	}
	p.Sons = append(p.Sons, son)
	return p
}
func (p *Page) AddSons(sons ...*Page) *Page {
	for _, son := range sons {
		p.AddSon(son)
	}
	return p
}

var pages []*Page

func AddPage(page *Page) {
	if pages == nil {
		pages = make([]*Page, 0)
	}
	pages = append(pages, page)
}

func RegPages() {
	//todo 数据指纹对比，如果没有变更就不更新

	// 页面权限注册接口
	conf := config.GetService()
	authHost := conf.Register.Host
	var regUrlPage = fmt.Sprintf("http://%s/auth/admin/Page/_reg?app=%s", authHost, conf.App.Id)
	if !config.GetCore().IsDev {
		//从文件获取配置
		pages = make([]*Page, 0)
		content := ez.ReadFile(confFilePage)
		errs.Try(json.Unmarshal(content, &pages))
		lastMd5 := ez.ReadFile(confFilePageMd5)
		nowMd5 := ez.Md5(string(content))
		if string(lastMd5) == nowMd5 {
			return
		} else {
			ez.CreateFile(confFilePageMd5, []byte(nowMd5))
		}
	}

	if pages == nil {
		ez.Debug("页面为空")
		errs.Create("页面为空")
		return
	}
	ez.Debug(fmt.Sprintf("前端页面注册地址：%s", regUrlPage))
	for _, data := range pages {
		content, e := json.Marshal(data)
		resp, e := http.PostForm(regUrlPage, url.Values{"content": []string{string(content)}})
		if ez.PrintError(e) {
			return
		}
		if resp != nil {
			rst, err := io.ReadAll(resp.Body)
			if ez.PrintError(err) {
				return
			}
			_, err = os.Stdout.Write(rst)
			ez.PrintError(err)
		}
	}

}

func CreatePageConfigFile() {
	if config.GetCore().IsDev {
		content, _ := json.MarshalIndent(pages, "", "\t")
		ez.CreateFile(confFilePage, content)
	}
}
